<?

 define ('MODEL_USER_CHECK_ACCESS',			'SELECT count(*) as `access` FROM `users_rights` WHERE `user_id` = ? AND `id` = ?');
 define ('MODEL_USER_SAVE_RULES',			'INSERT INTO `users_rights` (`user_id` ,`id`) VALUES (?, ?) ');
 define ('MODEL_USER_DELETE_USER_RIGHTS',	'DELETE FROM `users_rights` WHERE `user_id` = ?');
 
 define	('MODEL_USER_ADD_FEED',				'INSERT INTO `feeds` (`object` ,`user_id`) VALUES (?, ?)');
 define	('MODEL_USER_GET_FEED',				'SELECT * FROM `feeds` WHERE `object` =? AND `user_id` = ?' );
 define	('MODEL_USER_DELETE_FEED',			'DELETE FROM `feeds` WHERE `object` = ? AND `user_id` = ?' );
 
 define ('MODEL_USER_DELETE',				'DELETE FROM  `users` WHERE `login` =  ?');
 
 class Model_Admin_User extends Model_User {
 	
 	protected $_type;
 	
 	function __construct() {
 		parent::__construct();	
 	
 		$this->_type = 1;
 	}

	function login($username,$password) {

		$user = $this->find(array(login => $username));

		if(empty($user))
			throw new UserException ('wrong_pair_login_password');
		
		$this->init($user->id);

//print "<pre>";
//print_r($this->info->enabled);

		if(!$this->info->enabled)
			throw new UserException ('user_blocked');
		
		if(!$this->checkPassword($password)) 
			throw new UserException ('wrong_pair_login_password');

		$session = new Model_Session();
		
		$SID = $session->create($this->id, $this->_type);
		
		$this->logged = true;
		
		return $SID;
		
	} 
	
	function checkAccess($id) {
		if(_DEBUG)
			error_log("CHECKING: user: ".$this->id.", partition: ".$id);		
	
		return $this->getRow(MODEL_USER_CHECK_ACCESS,array($this->id,$id))->access ? true : false;
	}
	
	function saveRules($rules, $uid) {

		$sth = $this->dbh->prepare(MODEL_USER_DELETE_USER_RIGHTS);
		$sth->execute(array($uid));

		$sth2 = $this->dbh->prepare(MODEL_USER_SAVE_RULES);
		
		foreach ($rules as $rule) {
			$sth2->execute(array($uid,$rule));
		}
		
	}

	function saveRule($rule,$uid) {
		$sth = $this->dbh->prepare(MODEL_USER_SAVE_RULES);
		$sth->execute(array($uid,$rule));
	}
	
	
 	function confirmEmail($code) {
		
		$sth = $this->dbh->prepare(MODEL_USER_CONFIRM_EMAIL);
		return $sth->execute(array($code));		
 	}	
 	
 	function sign($object) {
 		$this->insertRow(MODEL_USER_ADD_FEED,array($object,$this->id));
 	}
 	
 	function checkFeed($object) {
 		
//print "<pre>";
//print_r(MODEL_USER_GET_FEED);
//print_r(array($object,$this->id));
//print "</pre>";

 		return $this->getRow(MODEL_USER_GET_FEED,array($object,$this->id));
 	}
 	
 	function unSign($object)  {
 		
//print "<pre>";
//print_r(MODEL_USER_DELETE_FEED);
//print_r(array($object,$this->id));
//print "</pre>"; 	
 		$this->execute(MODEL_USER_DELETE_FEED,array($object,$this->id));
 	}
 	
 	function delete($user) {
 		$this->execute(MODEL_USER_DELETE,array($user));
 	}
 }
?>